<template>
  <div class="updata-photo">
    <!-- <van-image
    class="img"
      :src="img"
      ref="img" /> -->
      <img class="img" :src="img" ref="img">

      <div class="toolbar">
        <span>取消</span>
        <span @click="onConfirm">完成</span>
      </div>
  </div>
</template>

<script>

import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'

import { updateUserPhoto } from '@/api/user.js'
export default {
  name: 'UpdataPhoto',
  props: {
    img: {
      type: [String, Object],
      required: true
    }

  },
  data () {
    return {
      cropper: {}
    }
  },
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move', // 拖动模式
      aspectRatio: 1, // 截图比列
      autoCropArea: 1, // 自动截取区域
      cropBoxMovable: false, // 截图区域是否能移动
      cropBoxResizable: false, // 截图区域缩放
      background: false, // 背景
      movable: true // 画布是否可以移动
    })
  },
  methods: {
    onConfirm () {
      // 获取裁剪区域的两种方式
      // console.log(this.cropper.getData())
      this.cropper.getCroppedCanvas().toBlob(blob => {
        console.log(blob)

        this.loadUpdataPhoto(blob)
      })
    },

    async loadUpdataPhoto (blob) {
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        forbidClick: true, // 禁用背景点击
        loadingType: 'spinner',
        message: '保存中'
      })
      try {
        // 如果 Content-Type 要求是application/json，则 data 传普通对象 {}
        // 如果 Content-Type 要求是multipart/form-data，则 data 传 FormData 对象
        // 纵观所有数据接口，你会发现大多数的接口都要求 Content-Type 要求是application/json
        // 一般只有涉及到文件上传的数据接口才要求Content-Type 要求是multipart/form-data
        // 这个时候传递一个 FormData 对象

        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await updateUserPhoto(formData)
        console.log(data)

        // 关闭弹层
        this.$emit('close')
        // 更新视图
        this.$emit('updata-photo', data.data.photo)

        // 保存更新
        this.$toast.success('保存成功')
      } catch (err) {
        this.$toast.fail('保存失败')
      }
    }

  }
}
</script>

<style lang="less" scoped>
.updata-photo{
  background-color: rgba(24, 18, 18, 0.603);
  height: 100%;
  .toolbar{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    padding: 30px;
    font-size: 30px;
    span{
      width: 90px;
      height: 90px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .img{
     display: block;

  /* This rule is very important, please don't ignore this */
     max-width: 100%;
  }
}
</style>
